import React from 'react';
import { createModalContainer } from '@/components/changeModal';
import {Form, Input,Button,Radio, message,Spin} from 'antd';
import { connect } from 'dva';
import styles from './index.less';
const RadioGroup = Radio.Group;

const FormItem = Form.Item;
@Form.create()
class EditPointComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state ={
            isFetching: false,
            value: parseInt(props.pointRule.RuleType),
            radioOneValue: '',
            radioTwoValue: '',
            loading:true
        }
    }

    componentWillMount() {
      window.Isoption = false;
        this.findPointRule(this.props.param.id)
    }
    componentDidMount() {
      window.Isoption = true;
    }

    findPointRule = id => {
        const { dispatch} = this.props;
        dispatch({
            type: 'gradeCard/FindPointRule',
            payload: {
                Id: id
            },
            callBack: {
                success: res => {
                    if(res.Code ===0) {
                        this.setState({
                            editData: res.Data,
                            value: res.Data.RuleType,
                            loading:false
                        })
                    }
                },
                error: res => {
                  this.setState({
                  loading:false
                  })
                  message.error(res.Msg)
                }
            }
        });
    }

      //取消
      handleCancel =() => {
        this.props.cancel();
     }

    onChangeRadio =(e) => {
        const value = e.target.value;
        let nameValue = e.target.value ===1? 'radioOneValue': 'radioTwoValue';
        this.setState({
            value: value,
        },() => {
          this.props.form.validateFields([nameValue], { force: true });
        });
          if(value === 1) {
              // this.setState({
              //   radioTwoValue: ''
              // })
              this.props.form.setFieldsValue({
                radioTwoValue: ''
              })
          }if (value === 2) {
            // this.setState({
            //     radioOneValue: ''
            //   })
              this.props.form.setFieldsValue({
                radioOneValue: ''
              })
          }
    }

    handleSubmit =(e) => {
        const { dispatch } = this.props;
        this.setState({
            isFetching: true
        })
        e.preventDefault();
        this.props.form.validateFields(async (err, values) => {
            if(!err) {
                dispatch({
                    type:'gradeCard/UpdatePointRule',
                    payload: {
                        Id: this.props.param.id,
                        Points: parseInt(values.points),
                        RuleType: parseInt(values.ruleType),
                        PointsLimit: this.state.value ===1?values.radioOneValue/1: values.radioTwoValue/1,
                    },
                    callBack: {
                        success: res => {
                            if(res.Code ===0) {
                                message.success('编辑成功');
                                this.setState({
                                    isFetching: false
                                }, () => {
                                    this.props.ok();
                                })
                            }
                        },
                        error: res => {
                            this.setState({
                                isFetching: false
                            });
                            message.error(res.Msg)
                        }
                    }
                })
            } else {
                this.setState({
                    isFetching: false
                })
            }
        })
    }
0
    validator = (rule, value, callback) => {
      if(value==='' && this.state.value===1) {
          callback('请填写条件数值');
      }else if(value > 999999999 && this.state.value===1){
        callback('请填写小于999999999的数值');
      }
      callback();
    };

    validatorRadioTwoValue =(rule, value, callback) => {
      if(value==='' && this.state.value===2) {
        callback('请填写条件数值');
      }else if(value > 999999999 && this.state.value===2){
        callback('请填写小于999999999的数值');
      }
      callback();
    }

    render() {
        const {getFieldDecorator} = this.props.form;
        const {editData, value,loading} = this.state;
        const points = editData && editData.Points;
        const ruleType = editData && editData.RuleType;
        const radioOneValue = (editData && editData.RuleType === 1)?editData.PointsLimit: '';
        const radioTwoValue = (editData && editData.RuleType === 2)?editData.PointsLimit: '';
        const formItemLayout = {
            labelCol: {
              span: 6 ,
            },
            wrapperCol: {
              span: 8 ,
            },
          };
          const formItemLayout1 = {
            labelCol: {
              span: 6 ,
            },
            wrapperCol: {
              span: 18 ,
            },
          };
          const formItemLayout2 = {
            labelCol: {
              span: 7 ,
            },
            wrapperCol: {
              span: 16,
            },
          };
          const radioStyle = {
            display: 'block',
            height: '30px',
            lineHeight: '30px',
          };

        return (
          <Spin spinning={loading}>
            <Form style={{paddingTop: 24}} onSubmit={this.handleSubmit}>
                <FormItem
                    label="奖励分值"
                    {...formItemLayout}
                >
                    {getFieldDecorator('points', {
                        initialValue: points,
                        rules: [
                            {required: true, message: '奖励分值必须为正整数'},
                            {pattern: /^[1-9]\d*$/, message: '奖励分值必须为正整数'}
                        ]
                    })(
                        <Input />
                    )}
                </FormItem>
                <FormItem
                    label="奖励条件"
                    {...formItemLayout1}
                >
                    {getFieldDecorator('ruleType', {
                        initialValue: ruleType,
                        rules: [
                            {required: true, message: '奖励条件必填'},
                        ]
                      })(
                            <RadioGroup onChange={this.onChangeRadio} className={styles.integralRadio}>
                                <Radio  value={1} style={{marginBottom: 16}}>
                                    <FormItem
                                      label="每成功交易"
                                      colon={false}
                                      {...formItemLayout2}
                                    >
                                      {getFieldDecorator('radioOneValue', {
                                        initialValue: radioOneValue,
                                        rules: [
                                        //   {required: this.state.value===1, message: '请填写条件数值'},
                                          {pattern: /^[1-9]\d*$/, message: '请填写为正整数'},
                                          {validator: this.validator}
                                        ],
                                        // validateTrigger: 'onBlur'
                                      })(
                                        <Input
                                          style={{ width: 234}}
                                          addonAfter="笔"
                                          onChange={(e) => {
                                              this.setState({
                                                  radioOneValue: e.target.value
                                              })
                                          }}
                                          disabled={this.state.value !==1}
                                        />
                                      )}
                                    </FormItem>
                                </Radio>
                                <Radio  value={2}>
                                    <FormItem
                                      label="每购买金额"
                                      colon={false}
                                      {...formItemLayout2}
                                    >
                                      {getFieldDecorator('radioTwoValue', {
                                          initialValue: radioTwoValue,
                                           rules: [
                                            // {required: this.state.value===2, message: '请填写条件数值'},
                                            {pattern: /^(\d+|\d+\.\d{1,2})$/, message: '请填写大于0的数，最多两位小数'},
                                            {validator: this.validatorRadioTwoValue}
                                          ],
                                          // validateTrigger: 'onBlur'
                                      })(
                                        <Input
                                            style={{ width: 234}}
                                            addonAfter="元"
                                            onChange={(e) => {
                                                this.setState({
                                                    radioTwoValue: e.target.value
                                             })
                                            }}
                                            disabled={this.state.value !==2}
                                            // value={this.state.radioTwoValue}
                                        />
                                      )}
                                    </FormItem>
                                </Radio>
                          </RadioGroup>
                        )
                    }
                </FormItem>
                <FormItem className={styles.footBtn}>
                        <Button onClick={this.handleCancel} style={{marginRight: 16}}>
                            取消
                        </Button>
                        <Button
                            type="primary"
                            htmlType="submit"
                            loading={this.state.isFetching}
                        >
                            保存
                        </Button>
                    </FormItem>
            </Form>
          </Spin>
        )
    }
}

const EditPointRule = createModalContainer(
    connect(({gradeCard, global, loading}) => ({
        pointRule: gradeCard.pointRule,
    }))(EditPointComponent),
    true,
    true
);

export default EditPointRule;
